#include "ipc.h"
#include <sys/msg.h>

#define MSG_MAX_SIZE 512

typedef struct{
	long mtype;
	char mtext[MSG_MAX_SIZE];
} msg_t;

int pqin= -1;
int pqout= -1;

int qin = -1;
int qout = -1;

int ipc_open(char* filepath,char* argv[]){

	if ( (qin == -1 && (qin = msgget(getpid(),  0666|IPC_CREAT)) == -1) || 
		(qout== -1 && (qout = msgget(getpid()+1, 0666|IPC_CREAT)) == -1 )){
		printf("error1");
		exit(-21);
	}
	
	int ret;

	switch(ret=fork()){
		case -1:
			printf("error2");
			exit(-21);
		case 0:
			execve(filepath,argv,NULL);
		default:
			return ret;
	}
}



int ipc_msg_recive(int from, message_t* message){

	if( from==SERVER  && pqout==-1)
		pqout = msgget(getppid()+1, 0);

	int queue= from==SERVER? pqout : qin;
	msg_t msgp;
	int msg_size;

	if((msg_size=msgrcv(queue, &msgp, MSG_MAX_SIZE, from==SERVER? getpid() : 0 , 0 ))<0) return -2;

	int pid= from==SERVER? SERVER : msgp.mtype;

	char* text=malloc(msg_size);//FREE
	memcpy(text, msgp.mtext, msg_size);
	
	message->size=msg_size;
	message->text=text;
	return pid;

}


int ipc_msg_send(int pid, message_t* message){
  
	if( pid==SERVER  && pqin==-1)
			pqin = msgget(getppid(), 0);

	int queue= pid==SERVER? pqin : qout;
	msg_t msgp;
	msgp.mtype= pid==SERVER? getpid() : pid;

	memcpy(msgp.mtext, message->text, message->size);

	return msgsnd(queue, &msgp, message->size, 0);
	
}

void ipc_close(){
	if(qin != -1){
		msgctl(qin, IPC_RMID, NULL);
	}
	if(qout != -1){
		msgctl(qout, IPC_RMID, NULL);
	}
}
